package com.yndsoft.jc.supplier.utils;

import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

public class MaxLengthWatcher implements TextWatcher {

    private int maxLen = 0;
    private EditText editText = null;
    private TextView textView = null;

    public MaxLengthWatcher(int maxLen, EditText editText) {
        this(maxLen, editText, null);
    }

    public MaxLengthWatcher(int maxLen, EditText editText, TextView textView) {
        this.maxLen = maxLen;
        this.editText = editText;
        this.textView = textView;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        Editable editable = editText.getText();
        int len = editable.length();
        if (textView != null) {
            textView.setText("(" +len + "/" + maxLen + ")");
            textView.setTextColor(0xFF7D7D7D);
        }
        if (len == maxLen) {
            if (textView != null) {
                textView.setTextColor(0xFFFF0000);
            }
        }
        if (len > maxLen) {
            int selEndIndex = Selection.getSelectionEnd(editable);
            String str = editable.toString();
            //截取新字符串
            String newStr = str.substring(0, maxLen);
            editText.setText(newStr);
            editable = editText.getText();

            //新字符串的长度
            int newLen = editable.length();

            //旧光标位置超过字符串长度
            if (selEndIndex > newLen) {
                selEndIndex = editable.length();
            }
            //设置新光标所在的位置
            Selection.setSelection(editable, selEndIndex);

        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
